import {Controller, Get, Param} from '@nestjs/common';
import {appName, clientIp as ip, getConfigManager, currentInstance, metadata, nacosNamingClient} from '../nacosClient';
import {ConfigManager} from '../nacosClient/configManager';

@Controller('/actuator')
export class ActuatorController {

  private configManager: ConfigManager;

  constructor() {
    this.configManager = getConfigManager();
  }


  @Get('/health')
  async health() {
    const nacosNamingClientStatus = await nacosNamingClient.getServerStatus();
    return {
      status: nacosNamingClientStatus
    };
  }

  @Get('/info')
  async info() {
    return {
      app: {
        name: appName,
        port: currentInstance.port,
        ip,
        metadata
      }
    };
  }

  @Get('/config')
  async config() {
    const properties = await this.configManager.getAllConfig();
    this.formatValue(properties);

    return {
      definitions: this.configManager.getSharedConfig(),
      properties
    };
  }

  @Get('/nacosNaming/instance/:serviceName')
  async instance(@Param('serviceName') serviceName: string) {
    return nacosNamingClient.getAllInstances(serviceName);
  }

  private formatValue(config: { [key: string]: any }, sensitiveKey?: boolean): void {
    for (const key of Object.keys(config)) {
      const value = config[key];
      sensitiveKey = sensitiveKey !== undefined && sensitiveKey ? sensitiveKey : ActuatorController.sensitiveKey(key);
      if (typeof value === 'object') {
        this.formatValue(value, sensitiveKey);
      } else if (typeof value === 'string' && sensitiveKey) {
        config[key] = '******';
      }
    }
  }

  private static sensitiveKey(key: string): boolean {
    return key.includes('password') || key.includes('security') || key.includes('key') || key.includes('token');
  }
}
